package com.mi.soul.whale.module.system.service.impl;

import com.mi.rule.cache.CacheKit;
import com.mi.rule.db.core.MiWrapper;
import com.mi.rule.db.dao.MiDao;
import com.mi.soul.whale.module.system.mapper.SysMapper;
import com.mi.soul.whale.module.system.service.DictService;
import com.mi.soul.whale.mybatis.entity.SysDict;
import com.mi.soul.whale.mybatis.entity.SysResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典表 服务实现类
 */
@Service
public class DictServiceImpl implements DictService {
    @Autowired
    private MiDao miDao;
    @Autowired
    private SysMapper sysMapper;

    @Override
    public SysDict getDict(String dictCode) {
        List<SysDict> dictList = getDictList();
        List<SysDict> list = dictList.stream().filter(it -> it.getCode().equals(dictCode)).collect(Collectors.toList());
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<SysDict> getDictList(String dictCode) {
        List<SysDict> dictList = getDictList();
        return dictList.stream().filter(it -> it.getCode().equals(dictCode)).collect(Collectors.toList());
    }

    @Override
    public List<SysDict> getDictList() {
        Object o = CacheKit.get("cache-system-dict-list");
        if (o == null) {
            List<SysDict> list = miDao.list(SysDict.class);
            CacheKit.set("cache-system-dict-list", list);
            return list;
        }
        return (List<SysDict>) o;
    }

    @Override
    public String getValue(String dictCode) {
        return getValue(dictCode, null);
    }

    @Override
    public String getValue(String dictCode, String defaultValue) {
        List<SysDict> dictList = getDictList();
        List<SysDict> list = dictList.stream().filter(it -> it.getCode().equals(dictCode)).collect(Collectors.toList());
        if (list.size() > 0) {
            return list.get(0).getValue();
        }
        return defaultValue;
    }

    @Override
    public long setValue(String dictCode, String value) {
        //更新数据
        MiWrapper<SysDict> wrapper = new MiWrapper<>(SysDict.class);
        wrapper.eq(SysDict.CODE, dictCode);
        SysDict dict = new SysDict();
        dict.setValue(value);
        long update = miDao.update(dict, wrapper);

        //清除缓存
        CacheKit.delete("cache-system-dict-list");

        return update;
    }
}
